﻿using Ledict.ConditionExtract.Base;
using Ledict.ConditionExtract.BLL;
using Ledict.ConditionExtract.Common;
using Ledict.ConditionExtract.Model;
using Ledict.Utility.Msg;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Ledict.ConditionExtract.Frm.NodeTree
{
    /// <summary>
    /// 默认来源配置
    /// </summary>
    public partial class AddFrmSourceDefaultSetting : BaseForm
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        public AddFrmSourceDefaultSetting()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 父窗体选择树节点
        /// </summary>
        public TreeNode ClickNode { get; set; }

        /// <summary>
        /// 节点子类型名称
        /// </summary>
        public string CodeSubType = string.Empty;

        /// <summary>
        /// 一级节点类型
        /// </summary>
        public string CCNodeType = string.Empty;

        /// <summary>
        /// 来源默认配置表
        /// </summary>
        public DataTable sysExpressSourceDefaultSettingTable = new DataTable();

        NewIDBLL newid = new NewIDBLL();
        ArgumentTypeXmlBLL bll = new ArgumentTypeXmlBLL();
        ExpressSourceDefaultSettingsBLL esd = new ExpressSourceDefaultSettingsBLL();
        CaseCauseBLL casebll = new CaseCauseBLL();
        DataTable dtcaseCauseType = new DataTable();

        //获取文书类型
        private LogicCaseTypeDocTypeRelationBLL caseTypeDocTypeRelationBll = new LogicCaseTypeDocTypeRelationBLL();
        private SYS_CaseType_DocType_LogicParagBLL sysCaseTypeDocTypeParagBll = new SYS_CaseType_DocType_LogicParagBLL();


        /// <summary>
        /// 加载事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void AddFrmSourceDefaultSetting_Load(object sender, EventArgs e)
        {
            //标题
            this.Text = "添加来源默认配置";
            DataTable dt = casebll.GetCaseCauseNodeType(ClickNode.Tag.ToString());
            if (dt != null && dt.Rows.Count > 0)
            {
                cmbConfigType.DataSource = dt;
                cmbConfigType.DisplayMember = "CC_NodeTypeName";
                cmbConfigType.ValueMember = "CC_NodeType";
            }
            dtcaseCauseType = casebll.GetCaseCauseTypeByNodeType();
            //加载用途
            LoadPurposeList();
            //加载版本
            LoadVersionList();
            //加载 第一级来源树+相关信息单元
            LoadSourceTree();
            //来源与逻辑段和版本不可用
            this.groupBox1.Enabled = false;
            this.groupBox9.Enabled = false;

            Tree_Source.ForeColor = System.Drawing.Color.Gray;


            //构造来源默认配置表
            gdvSourceDefaultSetting.AutoGenerateColumns = false;
            gdvSourceDefaultSetting.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;

            sysExpressSourceDefaultSettingTable.Columns.Add("DS_ID", typeof(string));
            sysExpressSourceDefaultSettingTable.Columns.Add("CC_NodeSubType", typeof(string));
            sysExpressSourceDefaultSettingTable.Columns.Add("CC_NodeType", typeof(string));
            sysExpressSourceDefaultSettingTable.Columns.Add("ES_PurposeID", typeof(string));
            sysExpressSourceDefaultSettingTable.Columns.Add("ES_PurposeName", typeof(string));
            sysExpressSourceDefaultSettingTable.Columns.Add("CD_Code", typeof(string));
            sysExpressSourceDefaultSettingTable.Columns.Add("CD_Name", typeof(string));
            sysExpressSourceDefaultSettingTable.Columns.Add("CDL_Code", typeof(string));
            sysExpressSourceDefaultSettingTable.Columns.Add("CDL_Name", typeof(string));
            sysExpressSourceDefaultSettingTable.Columns.Add("TextType_Code", typeof(string));
            sysExpressSourceDefaultSettingTable.Columns.Add("TextType_Name", typeof(string));
            sysExpressSourceDefaultSettingTable.Columns.Add("ConfigName", typeof(string));
            sysExpressSourceDefaultSettingTable.Columns.Add("PublicSourceID", typeof(string));
            sysExpressSourceDefaultSettingTable.Columns.Add("Public_InfoName", typeof(string));


            this.Tree_Source.HideSelection = false;
            this.Tree_Source.DrawMode = TreeViewDrawMode.OwnerDrawText;
            this.Tree_Source.DrawNode += new DrawTreeNodeEventHandler(treeView1_DrawNode);
        }

        private void treeView1_DrawNode(object sender, DrawTreeNodeEventArgs e)
        {
            e.DrawDefault = true; //我这里用默认颜色即可，只需要在TreeView失去焦点时选中节点仍然突显
            return;
        }

        /// <summary>
        /// 加载用途字典信息
        /// </summary>
        private void LoadPurposeList()
        {
            //获取用途类型下的字典列表
            var dt = bll.GetArgumentDtByType("Purpose");
            chkLstBox_Purpose.DataSource = dt;
            chkLstBox_Purpose.DisplayMember = "AM_Name";
            chkLstBox_Purpose.ValueMember = "AM_ID";
            chkLstBox_Purpose.SelectedIndex = -1;
        }

        /// <summary>
        /// 加载版本字典
        /// </summary>
        private void LoadVersionList()
        {
            //获取用途类型下的字典列表
            var dt = bll.GetArgumentDtByType("TextType");
            chkListBox_Version.DataSource = dt;
            chkListBox_Version.DisplayMember = "AM_Name";
            chkListBox_Version.ValueMember = "AM_Code";
            chkListBox_Version.SelectedIndex = -1;
        }

        #region 对树的操作事件
        /// <summary>
        /// 加载 第一级来源树+相关信息单元
        /// </summary>
        private void LoadSourceTree()
        {
            TreeDataBLL trbll = new TreeDataBLL();
            DataTable dt = new DataTable();           
            if ((findParentNode(ClickNode).Text == "刑事罪名"))
            {
                dt = trbll.GetSourceTree_New("CT_Code in('a1','jb1','ja1') and CD_DocType=1 and CDR_IsAnalysableDoc=1");
            }
            else if ((findParentNode(ClickNode).Text == "民事案由"))
            {
                dt = trbll.GetSourceTree_New("CT_Code='b1' and (CD_DocType=1 and CDR_IsAnalysableDoc=1) or CD_DocType=5");
            }
            else if ((findParentNode(ClickNode).Text == "行政执法"))
            {
                dt = trbll.GetSourceTree_New("CT_Code='xzzf' and (CD_DocType=1 and CDR_IsAnalysableDoc=1) or CD_DocType=5");
            }
            #region MyRegion
            //if (dt != null && dt.Rows.Count > 0)
            //{
            //var list = dt.AsEnumerable().ToList();
            //if ((findParentNode(ClickNode).Text == "刑事罪名"))
            //{
            //    list1 = dt.Select("CT_Code in('a1','jb1','ja1') and CD_DocType=1 and CDR_IsAnalysableDoc=1");
            //}
            //else
            //{
            //    list1 = dt.Select("CT_Code='b1' and (CD_DocType=1 and CDR_IsAnalysableDoc=1) or CD_DocType=5");
            //}
            //var whereList =
            //    list.Where(
            //        x =>
            //            (x[1].ToString() == "a1" || x[1].ToString() == "b1") &&
            //            (x[6].ToString() == "1" || x[6].ToString() == "5") &&
            //            (x[13].ToString() == "1" || x[13] == DBNull.Value)).ToList();
            //DataTable dt = trbll.GetSourceTree_New();
            //DataRow[] arrayDr = dt.Select();

            //  foreach (DataRow caseTreeNodeRode in list.Where(x => (x[1].ToString() == "a1" || x[1].ToString() == "b1") && (x[6].ToString() == "1" || x[6].ToString() == "5") && (x[13].ToString() == "1" || x[13] == DBNull.Value)))

            #endregion   
            if (dt != null && dt.Rows.Count > 0)
            {
                foreach (DataRow caseTreeNodeRode in dt.Rows)
                {
                    TreeNode node = new TreeNode
                    {
                        Text = LdFormat.ObjectToString(caseTreeNodeRode["CD_Name"]),//CD_Name,名称
                        Tag = caseTreeNodeRode["CD_ID"] + "," + caseTreeNodeRode["CD_CODE"]//CD_ID,CD_CODE
                    };
                    if (trbll.GetSourceTreeChild(caseTreeNodeRode["CD_ID"].ToString()).Rows.Count > 0)
                    {
                        node.Nodes.Add(new TreeNode());
                    }

                    Tree_Source.Nodes.Add(node);
                }
                #region 2017-11-2 ljj 解决基础数据部案例加工 增加的临时机制

                TreeNode nodeEx = new TreeNode
                {
                    Text = "裁判文书",//CD_Name,名称
                    Tag = "CD991106000000000,JudgeBook"//CD_ID,CD_CODE
                };
                nodeEx.Nodes.Add(new TreeNode());
                Tree_Source.Nodes.Add(nodeEx);
                #endregion
            }
        }

        /// <summary>
        /// 寻找顶级节点
        /// </summary>
        /// <param name="node"></param>
        /// <returns></returns>
        private TreeNode findParentNode(TreeNode node)
        {
            if (node.Parent == null)
            {
                return node;
            }
            else
            {
                return findParentNode(node.Parent);
            }
        }

        /// <summary>
        /// 展开树节点事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Tree_Source_AfterExpand(object sender, TreeViewEventArgs e)
        {
            e.Node.Nodes.Clear();
            //加载下级树
            BtnSourceTreeChild(e.Node, e.Node.Level);
        }

        /// <summary>
        /// 下级来源树
        /// </summary>
        /// <param name="parentNode">父节点</param>
        /// <param name="level">层级</param>
        private void BtnSourceTreeChild(TreeNode parentNode, int level)
        {
            TreeDataBLL trbll = new TreeDataBLL();
            var strArray = parentNode.Tag.ToString().Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);//ID,Code
            string pid = strArray[0];
            //DataTable caseTreeNodeRode = trbll.GetSourceTree(pid); //注释掉，不用ArgumentType和Argument表
            #region 2017-11-2 ljj 解决基础数据部案例加工 增加的临时机制
            if (pid == "CD991106000000000")// pid = "CD1709181032010818";//67 CD1609121111100001 160民事CD1709181032010818
            {
                DataTable dt = caseTypeDocTypeRelationBll.GetList();
                if (dt != null && dt.Rows.Count > 0)
                {
                    foreach (DataRow dr in dt.Rows)
                    {
                        TreeNode node = new TreeNode();
                        node.Text = LdFormat.ObjectToString(dr["LCR_Name"].ToString());
                        node.Tag = dr["CD_Code"] + "," + dr["LCR_ID"];
                        if (sysCaseTypeDocTypeParagBll.GetSysCaseTypeDocType(dr["CD_Code"].ToString(), "1").Rows.Count > 0)
                        {
                            node.Nodes.Add(new TreeNode());
                        }
                        parentNode.Nodes.Add(node);
                    }
                }
            }
            else if (parentNode.FullPath.StartsWith("裁判文书"))
            {
                DataTable dt = sysCaseTypeDocTypeParagBll.GetSysCaseTypeDocType(pid, level.ToString());
                if (dt != null && dt.Rows.Count > 0)
                {
                    foreach (DataRow dr in dt.Rows)
                    {
                        TreeNode node = new TreeNode();
                        node.Text = LdFormat.ObjectToString(dr["CDL_Name"].ToString());
                        node.Tag = dr["CDL_ID"] + "," + dr["CDL_Code"];
                        if (sysCaseTypeDocTypeParagBll.GetSysCaseTypeDocType(dr["CDL_ID"].ToString(), (level + 1).ToString()).Rows.Count > 0)
                        {
                            node.Nodes.Add(new TreeNode());
                        }
                        parentNode.Nodes.Add(node);
                    }
                }
            }
            else
            {
                #endregion
                DataTable caseTreeNodeRode = trbll.GetSourceTreeChild(pid, level + 1);
                if (caseTreeNodeRode.Rows.Count == 0)
                    return;
                for (int i = 0; i < caseTreeNodeRode.Rows.Count; i++)
                {
                    TreeNode node = new TreeNode();
                    //node.Text = LdFormat.ObjectToString(caseTreeNodeRode.Rows[i]["name"]);
                    //node.Tag = caseTreeNodeRode.Rows[i]["id"];

                    node.Text = LdFormat.ObjectToString(caseTreeNodeRode.Rows[i]["CDL_Name"]);
                    node.Tag = caseTreeNodeRode.Rows[i]["CDL_ID"] + "," + caseTreeNodeRode.Rows[i]["CDL_Code"];//ID,Code

                    if (trbll.GetSourceTreeChild(LdFormat.ObjectToString(caseTreeNodeRode.Rows[i]["CDL_ID"]), level + 2).Rows.Count > 0)
                    {
                        node.Nodes.Add(new TreeNode());
                    }
                    parentNode.Nodes.Add(node);
                }
            }
        }
        #endregion

        /// <summary>
        /// 版本选项点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void chkListBox_Version_Click(object sender, EventArgs e)
        {
            if (chkLstBox_Purpose.SelectedItems.Count == 1)
            {
                GetSourceDefaultSettingData();
            }
        }

        /// <summary>
        /// 用途列表单击事件 控制来源与逻辑段和版本展示
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void chkLstBox_Purpose_Click_1(object sender, EventArgs e)
        {
            if (chkLstBox_Purpose.SelectedItems.Count == 1)
            {
                groupBox1.Enabled = true;
                Tree_Source.ForeColor = System.Drawing.Color.Black;
            }
            else
            {
                groupBox1.Enabled = false;
                Tree_Source.ForeColor = System.Drawing.Color.Gray;

            }
        }

        /// <summary>
        /// 来源及逻辑段树选中事件 控制版本展示
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Tree_Source_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (!string.IsNullOrEmpty(this.Tree_Source.SelectedNode.Text))
            {
                groupBox9.Enabled = true;
            }
            else
            {
                groupBox9.Enabled = false;
            }
        }

        /// <summary>
        /// 清空选择内容
        /// </summary>
        public void clearInput()
        {
            //清除用途列表选项
            chkLstBox_Purpose.SelectedItems.Clear();
            //清除版本列表选项
            chkListBox_Version.SelectedItems.Clear();
            //清除来源及逻辑段选项
            Tree_Source.SelectedNode = null;
            //来源及逻辑段和版本选项为不可用状态
            groupBox1.Enabled = false;
            Tree_Source.ForeColor = System.Drawing.Color.Gray;
            groupBox9.Enabled = false;

            rbtnInfoNew.Checked = rbtnInfoCopy.Checked = false;
            lstBox.Enabled = false;
            lstBox.DataSource = null;

            gdvSourceDefaultSetting.ClearSelection();

            #region 清除checklistbox选中项
            //for (int j = 0; j < chkLstBox_Purpose1.Items.Count; j++)
            //{
            //    if (chkLstBox_Purpose1.GetItemChecked(j))
            //    {
            //        chkLstBox_Purpose1.SetItemChecked(j, false);
            //    }
            //}
            //清除版本列表选项
            //for (int j = 0; j < chkListBox_Version1.Items.Count; j++)
            //{
            //    if (chkListBox_Version1.GetItemChecked(j))
            //    {
            //        chkListBox_Version1.SetItemChecked(j, false);
            //    }
            //}
            ////清除来源及逻辑段选项
            //ClearTreeViewNodes(Tree_Source);
            //groupBox1.Enabled = false;
            //groupBox9.Enabled = false; 
            #endregion
        }

        /// <summary>
        /// 数据项列表删除数据事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void gdvSourceDefaultSetting_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0 && gdvSourceDefaultSetting.Rows.Count > 1 && !string.IsNullOrEmpty(gdvSourceDefaultSetting.Rows[e.RowIndex].Cells["DS_ID"].Value.ToString()))
            {
                if (MsgBox.Ask("您确定要删除本条信息吗？") == DialogResult.Yes)
                {

                    gdvSourceDefaultSetting.Rows.RemoveAt(e.RowIndex);
                }
            }
        }

        /// <summary>
        /// 保存默认配置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAdd_Click(object sender, EventArgs e)
        {
            string msg = string.Empty;
            string msg_exist = string.Empty;
            var iSuccess = 0;
            var iFail = 0;

            if (sysExpressSourceDefaultSettingTable != null && sysExpressSourceDefaultSettingTable.Rows.Count > 0)
            {
                for (int i = 0; i < sysExpressSourceDefaultSettingTable.Rows.Count; i++)
                {
                    SYS_Express_SourceDefaultSettings model = new SYS_Express_SourceDefaultSettings
                    {
                        DS_ID = sysExpressSourceDefaultSettingTable.Rows[i]["DS_ID"].ToString(),
                        CC_NodeSubType = sysExpressSourceDefaultSettingTable.Rows[i]["CC_NodeSubType"].ToString(),
                        CC_NodeType = sysExpressSourceDefaultSettingTable.Rows[i]["CC_NodeType"].ToString(),
                        ES_PurposeID = sysExpressSourceDefaultSettingTable.Rows[i]["ES_PurposeID"].ToString(),
                        ES_PurposeName = sysExpressSourceDefaultSettingTable.Rows[i]["ES_PurposeName"].ToString(),
                        CD_Code = sysExpressSourceDefaultSettingTable.Rows[i]["CD_Code"].ToString(),
                        CD_Name = sysExpressSourceDefaultSettingTable.Rows[i]["CD_Name"].ToString(),
                        CDL_Code = sysExpressSourceDefaultSettingTable.Rows[i]["CDL_Code"].ToString(),
                        CDL_Name = sysExpressSourceDefaultSettingTable.Rows[i]["CDL_Name"].ToString(),
                        TextType_Code = sysExpressSourceDefaultSettingTable.Rows[i]["TextType_Code"].ToString(),
                        TextType_Name = sysExpressSourceDefaultSettingTable.Rows[i]["TextType_Name"].ToString(),
                        PublicSourceID = sysExpressSourceDefaultSettingTable.Rows[i]["PublicSourceID"].ToString()
                    };
                    if (!esd.IsExistsData(model))
                    {
                        if (esd.AddExpressSourceDefault(model))
                        {
                            iSuccess++;
                        }
                        else
                        {
                            iFail++;
                        }
                    }
                    else
                    {
                        msg_exist += string.Format("配置类型{0},用途为{1}的规则已存在\r\n", cmbConfigType.Text, model.ES_PurposeName);
                        iFail++;
                    }
                }
                MsgBox.OK(string.Format("添加成功{0}条。\r\n失败{1}条。\r\n{2}", iSuccess, iFail, msg_exist.TrimEnd(',')));
                this.Close();
            }
        }


        /// <summary>
        /// 绑定默认来源设置列表
        /// </summary>
        public void GetSourceDefaultSettingData()
        {
            #region 判断来源及逻辑段和版本与用途是否选择正确
            //1.判断用途是否选择
            if (chkLstBox_Purpose.SelectedItems.Count <= 0)
            {
                MsgBox.Warn("请先选择规则用途");
                return;
            }
            //2.判断来源及逻辑树是否已选择
            if (Tree_Source.SelectedNode == null)
            {
                MsgBox.Warn("请先选择左边树节点");
                return;
            }
            //3.判断版本是否选择
            if (chkListBox_Version.SelectedItems.Count <= 0)
            {
                MsgBox.Warn("请先选择规则版本");
                return;
            }
            //4.新建和共用是否已选择
            if (!rbtnInfoNew.Checked && !rbtnInfoCopy.Checked)
            {
                MsgBox.Warn("请先选择信息单元后再试！");
                return;

            }
            //5.共用选择后是否选择下面的数据
            if (rbtnInfoCopy.Checked && lstBox.SelectedItem == null)
            {
                MsgBox.Warn("请选择公用信息单元后再试！");
                return;
            }
            #endregion
            //获取节点类型（一级还是二级）
            if (dtcaseCauseType.Select("CC_NodeType=" + cmbConfigType.SelectedValue.ToString()).Length > 0)
            {
                CodeSubType = cmbConfigType.SelectedValue.ToString();
            }
            else
            {
                CCNodeType = cmbConfigType.SelectedValue.ToString();
            }
            //从上面规则中添加来源列表信息
            string parentid = string.Empty;
            string parentName = string.Empty;
            var strArray = new string[] { };
            var sourceParaId = string.Empty;
            string sourceParagraphName = string.Empty;

            if (Tree_Source.SelectedNode.FullPath.StartsWith("裁判文书"))
            {
                string[] res = Tree_Source.SelectedNode.FullPath.Replace("裁判文书\\", "").Split(new string[] { "\\" }, StringSplitOptions.RemoveEmptyEntries);
                TreeNode tn = FindNodeByText(FindParentNode(Tree_Source.SelectedNode), res[0].Trim());
                parentName = tn.Text;
                strArray = tn.Tag.ToString().Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                parentid = strArray[0];
            }
            else
            {
                string[] res = Tree_Source.SelectedNode.FullPath.Split(new string[] { "\\" }, StringSplitOptions.RemoveEmptyEntries);
                TreeNode tn = FindNodeByText(FindParentNode(Tree_Source.SelectedNode), res[0].Trim());
                parentName = tn.Text;
                strArray = tn.Tag.ToString().Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                parentid = strArray[1];
            }

            //if (Tree_Source.SelectedNode.Level == 1)
            //{
            //    parentName = Tree_Source.SelectedNode.Parent.Text;
            //    strArray = Tree_Source.SelectedNode.Parent.Tag.ToString().Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
            //    parentid = strArray[1];
            //}
            //else if (Tree_Source.SelectedNode.Level == 2)
            //{
            //    parentName = Tree_Source.SelectedNode.Parent.Parent.Text;
            //    strArray = Tree_Source.SelectedNode.Parent.Parent.Tag.ToString().Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
            //    parentid = strArray[1];
            //}
            //else
            //{
            //    parentName = Tree_Source.SelectedNode.Text;
            //    strArray = Tree_Source.SelectedNode.Tag.ToString().Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
            //    parentid = strArray[1];
            //}

            sourceParaId =
                Tree_Source.SelectedNode.Tag.ToString().Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries)[1];
            sourceParagraphName = Tree_Source.SelectedNode.Text;
            DataRow dr = sysExpressSourceDefaultSettingTable.NewRow();
            dr["DS_ID"] = newid.JudgeDoc_CreateID("SYS_Express_Source");
            dr["CC_NodeSubType"] = !string.IsNullOrEmpty(CodeSubType) ? CodeSubType : "";
            dr["CC_NodeType"] = !string.IsNullOrEmpty(CodeSubType) ? CodeSubType : CCNodeType;
            dr["ES_PurposeID"] = ((DataRowView)this.chkLstBox_Purpose.SelectedItem).Row[0].ToString();
            dr["ES_PurposeName"] = ((DataRowView)this.chkLstBox_Purpose.SelectedItem).Row[1].ToString();
            dr["CD_Code"] = parentid;
            dr["CD_Name"] = parentName;
            dr["CDL_Code"] = sourceParaId;
            dr["CDL_Name"] = sourceParagraphName;
            dr["TextType_Code"] = ((DataRowView)this.chkListBox_Version.SelectedItem).Row[2].ToString();
            dr["TextType_Name"] = ((DataRowView)this.chkListBox_Version.SelectedItem).Row[1].ToString();
            dr["ConfigName"] = cmbConfigType.Text.ToString();
            string str = string.Empty;
            string strName = string.Empty;
            if (rbtnInfoNew.Checked)
            {
                str = "单一";
                strName = dr["DS_ID"].ToString();
            }
            else if (rbtnInfoCopy.Checked)
            {
                str = lstBox.DataSource != null ? ((DataRowView)lstBox.SelectedItem).Row[1].ToString() : string.Empty;
                strName = lstBox.DataSource != null ? ((DataRowView)lstBox.SelectedItem).Row[0].ToString() : string.Empty;
            }
            dr["PublicSourceID"] = strName;
            dr["Public_InfoName"] = str;
            if (!string.IsNullOrEmpty(dr["CC_NodeSubType"].ToString()))
            {
                DataRow[] drr = sysExpressSourceDefaultSettingTable.Select(string.Format("ES_PurposeID = '{0}' and CD_Code = '{1}' and CDL_Code = '{2}' and TextType_Code = '{3}' and  PublicSourceID='{4}' and CC_NodeSubType='{5}' ", dr["ES_PurposeID"], dr["CD_Code"], dr["CDL_Code"], dr["TextType_Code"], dr["PublicSourceID"], dr["CC_NodeSubType"]));
                if (drr.Length > 0)
                {
                    MsgBox.Err("配置表中已存在此规则，请重新选择！");
                    clearInput();
                    return;
                }
            }
            else if (!string.IsNullOrEmpty(dr["CC_NodeType"].ToString()))
            {
                DataRow[] drr = sysExpressSourceDefaultSettingTable.Select(string.Format("ES_PurposeID = '{0}' and CD_Code = '{1}' and CDL_Code = '{2}' and TextType_Code = '{3}' and  PublicSourceID='{4}' and CC_NodeType='{5}' ", dr["ES_PurposeID"], dr["CD_Code"], dr["CDL_Code"], dr["TextType_Code"], dr["PublicSourceID"], dr["CC_NodeType"]));
                if (drr.Length > 0)
                {
                    MsgBox.Err("配置表中已存在此规则，请重新选择！");
                    clearInput();
                    return;
                }
            }
            sysExpressSourceDefaultSettingTable.Rows.Add(dr);
            gdvSourceDefaultSetting.DataSource = sysExpressSourceDefaultSettingTable;
            clearInput();
        }

        /// <summary>
        /// 获取指定text值的节点
        /// </summary>
        /// <param name="tnParent">指定节点</param>
        /// <param name="strText">Text值</param>
        /// <returns></returns>
        private TreeNode FindNodeByText(TreeNode tree, string strText)
        {
            if (tree == null)
            {
                return null;
            }
            if (tree.Text == strText)
            {
                return tree;
            }
            TreeNode tnRet = null;
            foreach (TreeNode item in tree.Nodes)
            {
                tnRet = FindNodeByText(item, strText);
                if (tnRet != null) break;
            }
            return tnRet;
        }

        private TreeNode FindParentNode(TreeNode node)
        {
            if (node.Parent != null)
            {
                if (!string.IsNullOrEmpty(node.Parent.Text) && node.Parent.Parent == null)
                {
                    return node.Parent;
                }
                else
                {
                    return findParentNode(node.Parent);
                }
            }
            else
            {
                return node;
            }
        }

        /// <summary>
        /// 窗体关闭事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void AddFrmSourceDefaultSetting_FormClosing(object sender, FormClosingEventArgs e)
        {
            DialogResult = DialogResult.Yes;
        }




        #region 清理树节点
        //public void ClearTreeViewNodes(TreeView tv)
        //{
        //    Tree_Source.AfterCheck -= Tree_Source_AfterCheck_1;

        //    foreach (TreeNode node in tv.Nodes)
        //    {
        //        node.Checked = false;
        //        ChildrenChecked(node);
        //    }
        //    Tree_Source.AfterCheck += Tree_Source_AfterCheck_1;

        //}

        //private void ChildrenChecked(TreeNode node)
        //{
        //    if (node.Nodes.Count > 0)
        //    {
        //        // int i = 0;
        //        for (int i = 0; i <= node.Nodes.Count - 1; i++)
        //        {
        //            node.Nodes[i].Checked = false;
        //            ChildrenChecked(node.Nodes[i]);
        //        }
        //    }
        //}
        #endregion

        //确定按钮事件
        private void btnSure_Click(object sender, EventArgs e)
        {
            //用途，版本已经选择了1个
            if (cmbConfigType.SelectedValue != null && chkLstBox_Purpose.SelectedItems.Count == 1 && chkListBox_Version.SelectedItems.Count == 1)
            {
                GetSourceDefaultSettingData();
            }
            else
            {
                MessageBox.Show("请检查配置类型，用途，版本是否已选择！");
                return;
            }
        }



        /// <summary>
        ///共用按钮选中事件
        /// </summary>
        private void rbtnInfoCopy_CheckedChanged(object sender, EventArgs e)
        {
            if (rbtnInfoCopy.Checked)
            {
                lstBox.Enabled = true;
                string str = string.Empty;
                if (cmbConfigType.SelectedValue != null && dtcaseCauseType.Select(" CC_NodeType= " + cmbConfigType.SelectedValue).Length > 0)
                {
                    str = "CC_NodeSubType='" + cmbConfigType.SelectedValue.ToString() + "'";
                }
                else
                {
                    str = "CC_NodeType='" + cmbConfigType.SelectedValue.ToString() + "'";
                }
                DataTable dt = esd.GetpublicInformation(str);
                if (sysExpressSourceDefaultSettingTable != null && sysExpressSourceDefaultSettingTable.Select(str).Length > 0)
                {
                    DataTable dt1 = sysExpressSourceDefaultSettingTable.Select(str).CopyToDataTable();
                    foreach (DataRow item in dt1.Rows)
                    {
                        DataRow dr = dt.NewRow();
                        dr["DS_ID"] = item["PublicSourceID"].ToString() == "单一" ? item["DS_ID"].ToString() : item["PublicSourceID"].ToString();
                        dr["publicName"] = item["CD_Name"] + "-" + item["CDL_Name"] + "(用途:" + item["ES_PurposeName"] + ";版本:" + item["TextType_Name"] + ")";
                        dt.Rows.Add(dr);
                    }
                }
                if (dt != null && dt.Rows.Count > 0)
                {
                    lstBox.DataSource = dt;
                    lstBox.DisplayMember = "publicName"; //设置显示列
                    lstBox.ValueMember = "DS_ID";//设置实际值
                    lstBox.SelectedItems.Clear();
                }
                else
                {
                    MsgBox.Warn("没有可用的信息单元！");
                    rbtnInfoCopy.Checked = true;
                }
            }

            //if (dt != null && dt.Rows.Count > 0)
            //{
            //    lstBox.DataSource = dt;
            //    lstBox.DisplayMember = "InfoName";//设置显示列
            //    lstBox.ValueMember = "CC_RegexInfoCode";//设置实际值
            //    lstBox.SelectedItems.Clear();
            //}
            //else
            //{
            //    MsgBox.Warn("没有可用的信息单元！");
            //    rbtnInfoNew.Checked = true;
            //}
        }

        /// <summary>
        /// 新建按钮选择事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void rbtnInfoNew_CheckedChanged(object sender, EventArgs e)
        {
            lstBox.Enabled = false;
            lstBox.DataSource = null;
        }
    }
}
